package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
 * @Author Justin Parker
 * @Date 2024/7/18 0018 17:32
 * @Version 1.0
 */
public class ChatServer {
    //构建服务端的ServerSocket对象
    private ServerSocket serverSocket;

    private static final int PORT;
    static {
        PORT = 8088;
    }
    public ChatServer() {
        try {
            System.out.println("服务器开始启动.....");
            serverSocket = new ServerSocket(PORT);
            System.out.println("服务器启动成功,正在"+PORT+"端口监听中.....");
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("服务器启动失败！");
            System.exit(-1);
        }
    }

    //启动服务读取数据
   public void start(){
      while (true){
      try {
          System.out.println("服务器正在等待客户端连接.....");
          Socket socket = serverSocket.accept();
          System.out.println("一个客户端连接了！");

          BufferedReader br = new BufferedReader(
                  new InputStreamReader(
                          socket.getInputStream(), StandardCharsets.UTF_8));

          String  line = null;
          while ((line = br.readLine() )!= null){
              System.out.println("客户端读取的数据："+line);
          }

      }catch (IOException e1){
//          System.out.println("服务器异常！"+e1.getMessage());
          e1.printStackTrace();
      }
}
    }
    public static void main(String[] args) {
        new ChatServer().start();
    }
}
